package com.cash.channel.svc.logic;

import com.aliyuncs.utils.StringUtils;
import com.cash.channel.api.exception.CashChannelException;
import geex.core.service.ProductService;
import geex.core.service.model.emuns.ProductTypeEnum;
import geex.core.service.model.product.Product;
import geex.core.service.model.product.SearchProductRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class ProductLogic {

    @Autowired
    private ChannelLogic channelLogic;

    @Autowired(required = false)
    private ProductService productService;

    public Product findProductById(Integer period, String productCode, String channel) throws CashChannelException {
        if (StringUtils.isNotEmpty(productCode)) {
            return productService.findProduct(productCode);
        }
        return findProductByPeriod(period, channel);
    }

    private Product findProductByPeriod(Integer period, String channel) throws CashChannelException {
        SearchProductRequest searchProductRequest = new SearchProductRequest();
        searchProductRequest.setProductType(ProductTypeEnum.XJD);
        searchProductRequest.setSetName(channelLogic.getChannelInfoByCode(channel).getcProductCode());
        searchProductRequest.setPage(1);
        List<Product> productList = productService.searchProduct(searchProductRequest);
        if(null==productList){
            throw new CashChannelException("未查询到对应产品信息");
        }
        log.info("产品列表" + productList);
        for (Product product : productList) {
            if (period.equals(product.getTenor())) {
                return product;
            }
        }
        throw new CashChannelException("未查询到对应产品信息");
    }

}
